<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品发布</title>

    <link rel="stylesheet" type="text/css" href="/css/header.css">
    <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="/css/release.css">
<body>
<div class="dingbu">
    <div class="denglu-font top">
        <!--        <a href="/" id="dingbuhome"><img src="/images/logo.jpg"></a>-->

        <!--        <div id="so" style="position: relative; left: 350px;top:8px;width: 100px; float: left;" class="top">-->
        <!--            <div class="input-group">-->
        <!--                <input type="text" class="form-control" id="searchText" style="width: 380px;">-->
        <!--                <span class="input-group-addon" id="search" onclick="search()"><i class="glyphicon glyphicon-search"-->
        <!--                                                                                  style="color: #0055aa;"> <span>搜索-->
        <!--                                </span></i></span>-->
        <!--            </div>-->
        <!--        </div>-->
        <div class="denglu-font2 top">
            <a href="/" id="dingbuhome">返回首页</a>
            <a href="/" id="wants">发布求购</a>
            <a href="/" id="cart">我的购物车</a>
            <a href="#" id="uname">zyl</a>
            <a href="login" id="login_logout">登录</a>
        </div>
        <div style="clear:both"></div>
    </div>
</div>

<!--<div class="list-1">-->
<!--    <ul class="list-ul-2" style="position: relative;right: 190px;">-->
<!--        <div class="img"><img src="/images/logo1.jpg" width="55px" height="55px" class="img-logo"/></div>-->

<!--        <li>-->
<!--            <a href="/" class="index_click">全部商品</a>-->
<!--        </li>-->
<!--        <li th:each="category:${categories}">-->
<!--            <a th:href="'/api/category/find?categoryId='+${category.id}" th:text="${category.name}"-->
<!--               class="category_click">123</a>-->
<!--        </li>-->
<!--        <li>-->
<!--            <a href="/api/wants/all" class="index_click">求购区</a>-->
<!--        </li>-->
<!--    </ul>-->
<!--</div>-->

<div id="app"><br><br>
    <div class="header">
            <span>
                <h2 style="position: relative;left: 150px;">商品发布</h2>
            </span>
    </div>
    <br><br>
    <div class="content">
        <table>
            <form id="form1" enctype="multipart/form-data">
                <tr>
                    <td class="text-right">请选择商品图片</td>
                    <td class="content_right">
                        <a href="javascript:;" class="file">
                            <input id="chooseimage" type="file" accept="image/png,image/gif,image/jpg,image/jpeg">
                            <img id="showimage" class="showimage" src="/images/addimage.png">
                        </a>
                    </td>
                </tr>
                <tr>
                    <td class="text-right">商品名称</td>
                    <td class="content_right"><input class="itemname" id="itemname" placeholder="请输入商品名称" required>
                    </td>
                </tr>
                <tr>
                    <td class="text-right">商品分类</td>
                    <td class="content_right">
                        <select class="category" id="category" title="请选择商品分类">
                            <option th:each="catagory:${categories}" th:id="${catagory.id}"
                                    th:text="${catagory.name}"></option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td class="text-right">商品描述</td>
                    <td class="content_right"><textarea class="description" rows="5" id="description" type="text"
                                                        placeholder="请输入商品描述"></textarea>
                        <!-- <input class="description" id="password" type="text" placeholder="请输入商品描述"></td> -->
                </tr>
                <tr>
                    <td class="text-right">新旧程度</td>
                    <td class="content_right" style="width: 500px">
                        <input class="level" id="level" type="range" min="1" max="10"
                               value="10" oninput="changelabel()" style="width: 30%;">
                        <p id="levellabel">全新</p>
                    </td>
                </tr>
                <tr>
                    <td class="text-right">价格</td>
                    <td class="content_right"><input class="price" id="price" type="number" required></td>
                </tr>
                <tr>
                    <td class="text-right">剩余数量</td>
                    <td class="content_right"><input class="price" id="count" type="number" required></td>
                </tr>

                <tr>
                    <td></td>
                    <td class="content_right">
                        <input type="button" class="btn btn-info" id="submit" value="立即提交">
                    </td>
                </tr>
            </form>
        </table>
    </div>
</div>
</body>
<script src="/jquery/jquery2.1.4.js"></script>
<script src="/layer/layer.js"></script>
<script>
    $('#login_logout').click(function () {
        localStorage.clear()
    })

    $(function () {

        load_data();

        $("#chooseimage").change(function () {
            if (checkFile() == false) {
                return;
            }
            var file = document.getElementById("chooseimage");
            $("#showimage").attr("src", getObjectURL($("#chooseimage")[0].files[0]));
        });

        $("#price").change(function () {
            if (checkPrice() == false) {
                layer.msg("请输入正确的价格");
                $(this).val("");
            }
        });

        $("#count").change(function () {
            if (checkCount() == false) {
                layer.msg("请输入正确的物品数量");
                $(this).val("");
            }
        });
        $("#category").change(function () {
            console.log($($(this).find('option:selected')).attr('id'))
            console.log($(this).val());
        });

        $("#submit").click(function () {
            var itemId = -1;
            var categoryId = []
            var userId = localStorage.getItem("userId");
            var itemname = $("#itemname").val();
            categoryId[0] = $($("#category").find('option:selected')).attr('id');
            var description = $("#description").val();
            var level = $("#level").val();
            var price = $("#price").val();
            var count = $("#count").val();
            // var formdata = new FormData($("#chooseimage")[0]);


            if (checkFile() != false && checkName() != false && checkPrice() != false && checkCount != false) {
                $.ajax({
                    url: "/api/item/release",
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json",
                    traditional: true,
                    data: JSON.stringify({
                        "userId": atob(userId),
                        "categoryIds": categoryId,
                        "itemName": itemname,
                        "description": description,
                        "level": level,
                        "price": price,
                        "count": count
                    }),
                    success: function (data) {
                        if (data.code == 0) {
                            itemId = data.data.itemId;
                            console.log(itemId);
                            if (itemId != -1) {
                                console.log("start transferring image")
                                var type = "image";
                                var formData = new FormData();
                                formData.append(type, $("#chooseimage")[0].files[0]);
                                $.ajax({
                                    url: "/api/item/upload?itemId=" + itemId,
                                    type: 'POST',
                                    data: formData,
                                    async: false,
                                    cache: false,
                                    contentType: false,
                                    processData: false,
                                    success: function (data) {
                                        location.assign("/api/user/info?userId=" + userId);
                                    },
                                    error: function (e) {
                                        var res = $.parseJSON(e.responseText);
                                        layer.msg(res.msg);
                                    }
                                });
                            }
                        } else {
                            layer.msg("fail!" + data.msg);
                        }
                    },
                    error: function () {

                    }

                });

            } else {
                layer.msg("商品发布失败！");
                return;
            }

        });

    });

    function load_data() {
        var theme = localStorage.getItem('username')
        var userId = localStorage.getItem('userId')
        console.log(localStorage.getItem('username'))
        console.log(localStorage.getItem('userId'))
        if (theme == null || theme == '') {
            $('#login_logout').text('登录')
            $('#uname').text('')
            $('#wants').hide()
            $('release').hide()
            $('#cart').hide()
        } else {
            $('#login_logout').text('退出')
            $('#login_logout').attr('href', '/logout')
            $('#uname').text(theme)
            $('#wants').show()
            $('#wants').attr('href', '/api/wants/release?userId=' + userId)
            $('#release').show()
            $('#release').attr('href', '/release')
            $('#cart').show()
            $('#cart').attr('href', '/api/cart/all?userId=' + userId)
            $('#uname').attr('href', '/api/user/info?userId=' + userId)
        }
    }

    function checkFile() {
        var $file1 = $("#chooseimage").val();
        if ($file1 == "") {
            layer.msg("请选择上传的目标文件! ")
            return false;
        }
        var fileName1 = $file1.substring($file1.lastIndexOf(".") + 1).toLowerCase();
        if (fileName1 != "png" && fileName1 != "jpg" && fileName1 != "gif" && fileName1 != "jpeg") {
            layer.msg("请选择上传图片! ")
            return false;
        }
        var size1 = $("#chooseimage")[0].files[0].size;
        if (size1 > 10485760) {
            alert("上传文件不能大于10M!");
            return false;
        }
        return true;
    }

    function changelabel() {
        var level = $("#level").val();
        if (level == 10) {
            $("#levellabel").text("全新");
        } else {
            $("#levellabel").text(level + "成新");
        }
    };

    function checkName() {
        var itemName = $("#itemname").val();
        if (itemName.length < 2) {
            return false;
        } else {
            return true;
        }
    }

    function checkPrice() {
        var price = $("#price").val() * 1;
        if (price == null || price == "" || price <= 0) {
            return false;
        } else {
            $("#price").val(price.toFixed(2));
        }
    }

    function checkCount() {
        var count = $("#count").val();
        if (count == null || count == "" || count <= 0) {
            return false;
        } else {
            $("#count").val(Math.trunc(count));
            return true;
        }
    }


    function checkName() {
        var itemName = $("#itemname").val();
        if (itemName.length < 2) {
            return false;
        } else {
            return true;
        }
    }

    function getObjectURL(file) {
        var url = null
        if (window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(file)
        } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file)
        } else if (window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file)
        }
        return url;
    }


</script>

</html>
